package cn.christ.com.mobilesafe.engine;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ServiceInfo;
import android.graphics.drawable.Drawable;
import android.os.Debug;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import cn.christ.com.mobilesafe.R;
import cn.christ.com.mobilesafe.modle.ProcessInfo;

public class ProcessProvider {

    private static int flags;

    // 获取运行进程数
    public static int getRunningProcessCount(Context context) {
        // ActivityManager(任务管理器)
        // 1 获取任务管理器
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        // 2 可以获得正在运行进程列表
        List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
        if (runningAppProcesses != null) {
            return runningAppProcesses.size();
        }
        return 0;
    }

    // 统计所有进程数
    public static int getAllProcessCount(Context context) {
        // Application,Activity,Service,ContentProvider,BroadcastReceiver
        // processName:基本都是同一个：怎么样排重：HashSet
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> infos = pm.getInstalledPackages(0);
        HashSet<String> set = new HashSet<String>();
        for (PackageInfo info : infos) {
            // Application
            set.add(info.applicationInfo.processName);
            // Activity
            ActivityInfo[] activities = info.activities;
            if (activities != null) {
                for (int i = 0; i < activities.length; i++) {
                    set.add(activities[i].processName);
                }
            }
            // Service
            ServiceInfo[] services = info.services;
            if (services != null) {
                for (int i = 0; i < services.length; i++) {
                    set.add(services[i].processName);
                }
            }
            // provider
            ProviderInfo[] providers = info.providers;
            if (providers != null) {
                for (int i = 0; i < providers.length; i++) {
                    set.add(providers[i].processName);
                }
            }
            // receiver
            ActivityInfo[] receivers = info.receivers;
            if (receivers != null) {
                for (int i = 0; i < receivers.length; i++) {
                    set.add(receivers[i].processName);
                }
            }
        }
        return set.size();
    }

    // 获取所用的内存
    public static long getAllMemory(Context context) {
        // 1 获取ActivityManager
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo outInfo = new MemoryInfo();
        am.getMemoryInfo(outInfo);
        return outInfo.totalMem;
    }

    // 占用内存
    public static long getUsedMemory(Context context) {
        // 1 获取ActivityManager
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo outInfo = new MemoryInfo();
        am.getMemoryInfo(outInfo);
        return outInfo.totalMem - outInfo.availMem;
    }

    /**
     * 获取正在所有运行App的进程信息
     */
    public static List<ProcessInfo> getAllProcessInfos(Context context) throws PackageManager.NameNotFoundException {
        //获取图标，进程名称，占用内存，是否系统进程，应用名称，进程是否杀不死
        //1.获取所有正在运行进程的信息
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
        //2.创建进程集合装运行进程
        ArrayList<ProcessInfo> infos = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        if (runningAppProcesses != null) {
            //3.进程给javabean赋值
            for (RunningAppProcessInfo info : runningAppProcesses) {
                String processName = info.processName;
                Debug.MemoryInfo processMemoryInfo = am.getProcessMemoryInfo(new int[]{info.pid})[0];
                int usedMemory = processMemoryInfo.getTotalPss() * 1024;
                ProcessInfo processInfo = new ProcessInfo();
                processInfo.usedMem = usedMemory;//3.2进程占用的内存
                try {
                    PackageInfo packageInfo = pm.getPackageInfo(processName, 0);
                    String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
                    Drawable icon = packageInfo.applicationInfo.loadIcon(pm);
                    flags = packageInfo.applicationInfo.flags;
                    if ((flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
                        processInfo.isSystem = true; //3.3进程是否系统的
                    } else {
                        processInfo.isSystem = false;
                    }
                    processInfo.appName = appName; //3.4进程的app名字
                    processInfo.icon = icon; //3.5进程的图标
                    // processInfo.isGodProcess=前台进程 || 可见进程 || 服务进程并且系统 || 后台进程
                    // || 系统
                    processInfo.isGodProcess = info.importance < 300 || info.importance == 300 && processInfo.isSystem
                            || info.importance == 400 && processInfo.isSystem;
                    infos.add(processInfo);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                    processInfo.isSystem = true;
                    processInfo.appName = processName;
                    processInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher);
                    processInfo.isGodProcess = true;
                    infos.add(processInfo);
                }

            }
        }

        return infos;
    }

    // 清理进程
    public static void killBackGroundProcess(Context context, String packageName) {
        // 1
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        // 进程的分类：空进程，后台进程，服务进程，可见进程，前台进程
        am.killBackgroundProcesses(packageName);
    }


}
